package com.example.customview.silder;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.example.customview.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class IndexBar extends View {
    private static final String[] DEFAULT_INDEX_ITEMS = {"A", "B", "C", "D", "E", "F", "G", "H",
            "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z","#"};


    private List<String> mIndexItems;
    private float mItemHeight; //每个index的高度
    private int mTextSize;      //sp
    private int mTextColor;
    private int mTextTouchedColor;

    private int mCurrentIndex = -1;

    private Paint mPaint;
    private Paint mTouchedPaint;
    private Paint mTextTouchBgPaint;
    private int mWidth;
    private int mHeight;
    private float mTopMargin;   //居中绘制，文字绘制起点和控件顶部的间隔
    private float mSpace =  dp2Px(getContext(),6);

    private TextView mOverlayTextView;
    private OnIndexTouchedChangedListener mOnIndexChangedListener;

    public IndexBar(Context context) {
        this(context, null);
    }

    public IndexBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public IndexBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        mIndexItems = new ArrayList<>();
        mIndexItems.addAll(Arrays.asList(DEFAULT_INDEX_ITEMS));
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TravelSideIndexBar);

        mTextSize = (int) ta.getDimension(R.styleable.TravelSideIndexBar_veBarTextSize, dp2Px(getContext(),11));
        mTextColor = ta.getColor(R.styleable.TravelSideIndexBar_veBarColor, Color.BLACK);
        mTextTouchedColor = ta.getColor(R.styleable.TravelSideIndexBar_veBarSelectColor,Color.BLACK);
        ta.recycle();
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setTextSize(mTextSize);
        mPaint.setColor(mTextColor);

        mTouchedPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTouchedPaint.setTextSize(mTextSize);
        mTouchedPaint.setColor(mTextTouchedColor);

        mTextTouchBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextTouchBgPaint.setColor(getResources().getColor(R.color.color_FF9549));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        String index;
        for (int i = 0; i < mIndexItems.size(); i++) {
            index = mIndexItems.get(i);
            Paint.FontMetrics fm = mPaint.getFontMetrics();


            if (i==mIndexItems.size()-1){
                canvas.drawText(index,
                        (mWidth - mPaint.measureText(index)) / 2,
                        mItemHeight / 2 + (fm.bottom - fm.top) / 2 - fm.bottom + mItemHeight * i + mTopMargin+mSpace,
                        mTouchedPaint);
            }else {
                canvas.drawCircle(mWidth/2 ,mItemHeight / 2 + (fm.bottom - fm.top) / 2 - fm.bottom + mItemHeight * i + mTopMargin+mSpace/2,dp2Px(getContext(),8),i == mCurrentIndex ? mTextTouchBgPaint : mTouchedPaint);
                canvas.drawText(index,
                        (mWidth - mPaint.measureText(index)) / 2,
                        mItemHeight / 2 + (fm.bottom - fm.top) / 2 - fm.bottom + mItemHeight * i + mTopMargin+mSpace,
                        i == mCurrentIndex ? mTouchedPaint : mPaint);
                     }


        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = getWidth();
        mHeight = h;
        mItemHeight = mHeight / mIndexItems.size();
        mTopMargin = (mHeight - mItemHeight * mIndexItems.size()) / 2;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Paint.FontMetrics fm = mPaint.getFontMetrics();
        mHeight = (int) (fm.bottom-fm.top)*mIndexItems.size();
        setMeasuredDimension(widthMeasureSpec,mHeight);
    }

    @Override
    public boolean performClick() {
        return super.performClick();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        performClick();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                float y = event.getY();
                int indexSize = mIndexItems.size();
                int touchedIndex = (int) (y / mItemHeight);
                if (touchedIndex < 0) {
                    touchedIndex = 0;
                } else if (touchedIndex >= indexSize) {
                    touchedIndex = indexSize - 1;
                }
                if (mOnIndexChangedListener != null && touchedIndex >= 0 && touchedIndex < indexSize) {
                    if (touchedIndex != mCurrentIndex&&touchedIndex!=mIndexItems.size()-1) {
                        mCurrentIndex = touchedIndex;
                        if (mOverlayTextView != null) {
                            mOverlayTextView.setVisibility(VISIBLE);
                            mOverlayTextView.setText(mIndexItems.get(touchedIndex));
                            Paint.FontMetrics fm = mPaint.getFontMetrics();
                            float yp = mItemHeight / 2 + (fm.bottom - fm.top) / 2 - fm.bottom + mItemHeight * mCurrentIndex + getTop() - mOverlayTextView.getHeight()/2;
                            mOverlayTextView.setY(yp);
                        }
                        mOnIndexChangedListener.onIndexChanged(mIndexItems.get(touchedIndex), touchedIndex);
                        invalidate();
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                mCurrentIndex = -1;
                if (mOverlayTextView != null) {
                    mOverlayTextView.setVisibility(GONE);
                }
                invalidate();
                break;
        }
        return true;
    }

    public void setItems(ArrayList<String> items){
        mIndexItems.clear();
        for (String letter:items){
            if(!mIndexItems.contains(letter)) {
                mIndexItems.add(letter);
            }
        }
        mHeight = 0;
        requestLayout();
    }

    public IndexBar setOverlayTextView(TextView overlay) {
        this.mOverlayTextView = overlay;
        return this;
    }

    public IndexBar setOnIndexChangedListener(OnIndexTouchedChangedListener listener) {
        this.mOnIndexChangedListener = listener;
        return this;
    }

    public interface OnIndexTouchedChangedListener {
        void onIndexChanged(String index, int position);
    }
    private int dp2Px (Context context,int dp){
        return (int) (context.getResources().getDisplayMetrics().density*dp+0.5);
    }
}
